﻿using DGIS.Map.Templetes;
using DGIS.Model;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DGIS.Map.UserControls
{
    /// <summary>
    /// SearchControl.xaml 的交互逻辑
    /// </summary>
    public partial class SearchControl : UserControl
    {
        public event ShowGSCloudExtent showGSCloudExtent;

        public event DrawGeometry drawGeomety;

        public event DrawPolygon drawPolygon;

        #region 局部变量

        private string _minLon;
        private string _maxLon;
        private string _minLat;
        private string _maxLat;
        private string _month;

        private string _minPath;
        private string _maxPath;
        private string _minRow;
        private string _maxRow;

        private DateTime _startDate;
        private DateTime _endDate;

        private int _pageIndex;
        private int _pageSize;
        private int _pageCount;

        private string _boundaryShpPath;

        private int _searchType;//当前影像查询方式类型

        private string _currentGSCloudId;//当前操作影像dataid
        private string _currentGSDatasetId = "";//当前查询影像类型id
        private string _currentGSDatasetType;//当前查询影像类型名称
        private string _searchGSDatasetType;//查询后影像类型名称(用于多线程下载时获取下载数据的扩展名)
        private List<GSCloud> _gsClouds;//当前查询结果
        private List<GSDataSet> _gsDataSets;//当前影像类型集合

        #endregion

        public SearchControl()
        {
            InitializeComponent();
            _pageSize = 10;
            this.StartDatePicker.SelectedDate = DateTime.Now.AddYears(-2);
            this.EndDatePicker.SelectedDate = DateTime.Now;

            GetGSDataSets();
        }

        #region 事件

        //查询按钮事件
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            _minLon = this.MinLonText.Text.Trim();
            _maxLon = this.MaxLonText.Text.Trim();
            _minLat = this.MinLatText.Text.Trim();
            _maxLat = this.MaxLatText.Text.Trim();

            _minPath = this.MinPathText.Text.Trim();
            _maxPath = this.MaxPathText.Text.Trim();
            _minRow = this.MinRowText.Text.Trim();
            _maxRow = this.MaxRowText.Text.Trim();

            _month = this.MonthCombox.SelectionBoxItem.ToString();

            _startDate = this.StartDatePicker.SelectedDate.Value;
            _endDate = this.EndDatePicker.SelectedDate.Value;

            _searchType = this.MainTabControl.SelectedIndex;
            if (string.IsNullOrEmpty(AppConstant.SearchPolygonStr) && _searchType == 3)
            {
                MessageBox.Show("请先在地图视图上选定查询的范围");
                return;
            }
            if (string.IsNullOrEmpty(AppConstant.SearchPolygonStr) && _searchType == 2)
            {
                MessageBox.Show("请先选择边界shp");
                return;
            }
            if (_currentGSDatasetId == "")
            {
                MessageBox.Show("请先选择检索数据集");
                return;
            }
            this.SearchButton.IsEnabled = false;
            this.ProgressBar.Visibility = Visibility.Visible;
            this.PaginationGrid.Visibility = Visibility.Hidden;

            Thread thread = new Thread(SearchGSCloud, 2048);
            thread.Start();
        }

        //绘制矩形
        private void DrawRectangleButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (drawGeomety != null)
                drawGeomety(2);
        }

        //绘制面
        private void DrawPolygonButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (drawGeomety != null)
                drawGeomety(3);
        }

        //浏览shp
        private void ScanShpButton_Click(object sender, RoutedEventArgs e)
        {
            //OpenFileDialog dlg = new OpenFileDialog()
            //{
            //    Filter = "shp|*.shp"
            //};
            //if (dlg.ShowDialog() == true)
            //{
            //    this.ScanShpPathTextbox.Text = dlg.FileName;
            //    _boundaryShpPath = dlg.FileName;

            //    DGIS.Service.IService.IGeometryService.IGeometryStructService geoStructService = new DGIS.Service.Service.GeometryService.GeometryStructService();
            //    string type;
            //    List<List<double[]>> points = geoStructService.GetShpPoints(_boundaryShpPath, out type);

            //    //地图绘制范围
            //    if (drawPolygon != null)
            //        drawPolygon(points[0]);
            //}
        }

        //数据集树选择事件
        private void LfTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            GSDataSet item = e.NewValue as GSDataSet;
            if (item.pid == "" || item.Children != null)
            {
                //MessageBox.Show("");
                return;
            }

            ComboBoxItem comboxItem = this.DataSetCombox.Items[0] as ComboBoxItem;
            comboBox.Height = 0;
            comboxItem.Content = item.dataname;
            _currentGSDatasetId = item.dataid;
            //_currentGSDatasetType = item.datatype;
        }


        //数据集下拉选择改变事件
        private void DataSetCombox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }

        //下载按钮事件
        private void Download_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ImageButton imgButton = sender as ImageButton;

            string dataid = imgButton.Tag.ToString();
            _currentGSCloudId = dataid;

            Thread thread = new Thread(DownloadGSCloudFile, 2048);
            thread.Start();
        }

        //上一页
        private void PrePage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ShowPages(_pageIndex - 1, _pageSize);
        }

        //下一页
        private void NextPage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ShowPages(_pageIndex + 1, _pageSize);
        }

        #endregion

        #region 方法

        /// <summary>
        /// 获取影像数据集
        /// </summary>
        private void GetGSDataSets()
        {
            DGIS.Control.GsCloudControl gsCloudControl = new Control.GsCloudControl();
            _gsDataSets = gsCloudControl.GetGSDataSetList();
            this.DataSetCombox.DataContext = _gsDataSets;
        }

        /// <summary>
        /// 检索在线影像(多线程调用)
        /// </summary>
        private void SearchGSCloud()
        {
            //_searchGSDatasetType = _currentGSDatasetType;
            bool showData = true;
            foreach (var dataSet in _gsDataSets)
            {
                if (dataSet.Children.Any(x => x.dataid == _currentGSDatasetId))
                {
                    showData = dataSet.dataid != "";
                    break;
                }
            }

            DGIS.Control.GsCloudControl gsCloudControl = new DGIS.Control.GsCloudControl();

            List<GSCloud> items = new List<GSCloud>();
            switch (_searchType)
            {
                case 0:
                    items = gsCloudControl.QueryImgListByLonLat(_startDate, _endDate, _month, _currentGSDatasetId.ToString(), _currentGSDatasetType, _minLon, _maxLon, _minLat, _maxLat, showData, ref AppConstant.CookieContainer);
                    break;
                case 1:
                    items = gsCloudControl.QueryImgListByPathRow(_startDate, _endDate, _month, _currentGSDatasetId.ToString(), _currentGSDatasetType, _minPath, _maxPath, _minRow, _maxRow, showData, ref AppConstant.CookieContainer);
                    break;
                case 2:
                    items = gsCloudControl.QueryImgListByPolygon(_startDate, _endDate, _month, _currentGSDatasetId.ToString(), _currentGSDatasetType, AppConstant.SearchPolygonStr, showData, ref AppConstant.CookieContainer);
                    break;
                case 3:
                    items = gsCloudControl.QueryImgListByPolygon(_startDate, _endDate, _month, _currentGSDatasetId.ToString(), _currentGSDatasetType, AppConstant.SearchPolygonStr, showData, ref AppConstant.CookieContainer);
                    break;
                default:
                    break;
            }

            //剔除不存在数据
            _gsClouds = items.Where(x => x.dataexists == 1).ToList();
            if (!_gsClouds.Any() && items.Any())
            {
                MessageBox.Show(string.Format("请求到{0}条数据，但没有可供下载数据", items.Count));
            }

            Console.WriteLine(_gsClouds.Count + "/" + items.Count);

            _pageCount = _gsClouds.Count / _pageSize;
            if (_gsClouds.Count % _pageSize != 0)
                _pageCount++;

            this.Dispatcher.Invoke(new Action(() =>
            {
                this.SearchButton.IsEnabled = true;
                this.ProgressBar.Visibility = Visibility.Hidden;
                this.TotalPageText.Text = _pageCount.ToString();
                this.PaginationGrid.Visibility = Visibility.Visible;

                ShowPages(0, _pageSize);
            }));
        }

        /// <summary>
        /// 显示分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        private void ShowPages(int pageIndex, int pageSize)
        {
            if (pageIndex >= _pageCount)
                pageIndex = _pageCount - 1;
            if (pageIndex < 0)
                pageIndex = 0;

            int index = pageIndex * _pageSize;
            int end = (pageIndex >= _pageCount - 1) ? _gsClouds.Count : (pageIndex + 1) * pageSize;

            this.CurrentPageText.Text = (pageIndex + 1).ToString();
            _pageIndex = pageIndex;

            List<GSCloud> items = new List<GSCloud>();
            for (int i = index; i < end; i++)
            {
                items.Add(_gsClouds[i]);
            }
            this.GsCloudDataGrid.ItemsSource = items;
            if (showGSCloudExtent != null)
                showGSCloudExtent(items);
        }

        /// <summary>
        /// 下载在线影像(多线程调用)
        /// </summary>
        private void DownloadGSCloudFile()
        {
            GSCloud item = _gsClouds.FirstOrDefault(x => x.dataid == _currentGSCloudId);
            item.filesize = (item.filesize == null) ? 0 : item.filesize;

            DGIS.Control.GsCloudControl gsCloudControl = new DGIS.Control.GsCloudControl();
            //string url = gsCloudControl.QueryImgDownloadUrl(item.dataid, _currentGSDatasetId.ToString(), ref AppConstant.CookieContainer);
            string url = item.url;

            if (AppConstant.DownloadProgressList.Any(x => x.Url == item.url))
            {
                MessageBox.Show("该任务已经存在");
            }
            else if (!string.IsNullOrEmpty(url))
            {
                DGIS.Control.DownloadControl downloadControl = new DGIS.Control.DownloadControl();
                List<DownloadFile> completeTasks = downloadControl.GetCompleteTasks();
                if (completeTasks.Any(x => x.Url == item.url))
                {
                    MessageBox.Show("已下载过该数据");
                }
                else
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        string extension;
                        BitmapImage ico;
                        GetDownloadFileTypeAndIco(out extension, out ico, _searchGSDatasetType);

                        if (item.filesize == null)
                            item.filesize = 0;

                        DownloadFile downloadItem = new DownloadFile()
                        {
                            FileName = item.dataid + extension,
                            FileSize = item.filesize.Value,
                            ProgressValue = -1,
                            Speed = 0,
                            IconSource = ico,
                            Url = url,
                            DataId = item.dataid
                        };

                        if (downloadControl.Download(downloadItem, false, true, ((id,status) =>
                        {
                            if (status == 3)
                            {
                                var fileTask = AppConstant.DownloadProgressList.FirstOrDefault(x => x.DataId == id);

                                System.Windows.Application.Current.Dispatcher.Invoke((Action)(()=> {
                                    AppConstant.DownloadProgressList.Remove(fileTask);
                                }));                                
                            }

                            return 0;
                        })))
                        {
                            AppConstant.DownloadProgressList.Add(downloadItem);
                        }
                        else
                        {
                            MessageBox.Show("下载失败");
                        }
                    }));
                }
            }
            else
            {
                MessageBox.Show("获取下载地址失败");
            }
        }

        /// <summary>
        /// 获取文件扩展名和图标
        /// </summary>
        /// <param name="extension"></param>
        /// <param name="icon"></param>
        /// <param name="gsDataSetType"></param>
        private void GetDownloadFileTypeAndIco(out string extension, out BitmapImage icon, string gsDataSetType)
        {
            icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory)));
            extension = ".tar.gz";
            return;

            //hdf文件
            if (gsDataSetType.Contains("MOD"))
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\hdf.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".hdf";
            }
            else if (gsDataSetType.Contains("MYD"))
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\hdf.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".hdf";
            }
            else if (gsDataSetType == "OLI_TIRS" || gsDataSetType == "L7slc-off" || gsDataSetType == "L7slc-on" || gsDataSetType == "L45TM" || gsDataSetType == "L45MSS" || gsDataSetType == "L123MSS" || gsDataSetType == "L45MSS")
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".tar.gz";
            }
            else if (gsDataSetType == "ali" || gsDataSetType.Contains("hyp"))
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\tgz.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".tgz";
            }
            else if (gsDataSetType == "co" || gsDataSetType == "no2" || gsDataSetType == "o3" || gsDataSetType == "pm10" || gsDataSetType == "pm25" || gsDataSetType == "so2")
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\bmp.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".tif";
            }
            else
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".zip";
            }
        }


        #endregion

    }
}
